<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

if(!function_exists('getRedirect')){
	/**
	 * 取得跳转链接
	 *
	 * @param string $defaultUrl 默认跳转页面
	 * @return string
	 */
	function getRedirect( $defaultUrl = null  ){
		if (isset($_REQUEST['redirect'])&&!empty($_REQUEST['redirect'])) {
			$redirect = trim( $_REQUEST['redirect'] );
		} else {
			$redirect = empty ($defaultUrl) ? null : $defaultUrl;
		}
		//$redirect = rawurldecode( $redirect );
		return $redirect;
	}
}

//显示状态图标
if(!function_exists('__st')){
	function __st($s){
		if($s){
			return base_url('images/admin/icons/tick.png');
		}else{
			return base_url('images/admin/icons/cross.png');
		}
	}
}
if(!function_exists('getUrl')){
	/**
	*	返回当前或者前一个页面的链接
	*	@param $current
	*	@return String
	*/
	function getUrl( $current = true ){
		if ( isset( $_SERVER['HTTP_REFERER'] ) && !$current ) {
			$url = $_SERVER['HTTP_REFERER'];
		} else {
			$url = $_SERVER['REQUEST_URI'];
		}
		return  $url;
	}
}

/**
 * 根据条件获取数组结果
 */
if (!function_exists('find_by_cond')) { 
    function find_by_cond($res, $cond,$index=false) { 
        foreach ($cond as $feild => $value) { 
            $rs = array (); 
            foreach ($res as $key => $val) { 
                if ($val[$feild] == $value) 
                    $rs[] = $val; 
            } 
            $res = $rs; 
        } 
         
        if(!empty($res) && $index!==false){ 
            if($index==-1) return array_pop($res); 
            return $res[$index];    
        } 
        return $res; 
    } 
} 

/**
 * 格式化分类列表
 * @param array $arr 要格式化的数组
 * @param int   $p  当前父分类ID
 * @return array
 */
if(!function_exists('format_tree')){
	function format_tree($arr,$p=0){ 
	    static $options = array(); 
	    if($p==0) $options = array(); 
	     
	    foreach( $arr as $key=>$val ){ 
	        if($val['parent_id']==$p){ 
	            $level = $p==0 ? 0 : $options[$val['parent_id']]['level']+1; 
	            $val['level'] = $level; 
	            $cates = find_by_cond( $arr,array('parent_id'=>$val['id']) ); 
	            $val['have_sub'] = count($cates); 
	            $options[$val['id']] = $val; 
	             
	            if(!empty($cates)){ 
	                foreach($cates as $k=>$v){ 
	                    $level = $options[$v['parent_id']]['level']+1; 
	                    $cates = find_by_cond( $arr,array('parent_id'=>$v['id']) ); 
	                    $v['have_sub'] = count($cates); 
	                    $v['level'] = $level; 
	                    $options[$v['id']] = $v; 
	                    format_tree($arr,$v['id']); 
	                } 
	            } 
	            unset($arr[$key]); 
	        } 
	    } 
	    return $options; 
	}
}

if (!function_exists('get_sub_tree')) { 
	function get_sub_tree($res, $catId, $level = 5, $isShowAll = true,&$result=array()) { 
		static $trees; 
		if (isset ($trees[$catId])) 
			return $trees[$catId]; 
			 
		foreach ($res as $key=>$_cat) { 
			if ($_cat['parent_id'] == $catId) { 
				if (!$isShowAll) { 
					if ($_cat['status'] != 1) 
						continue; 
				} 
				$result[] = $_cat; 
 				$parent_id = $_cat['id']; 
				unset($res[$key]); 
				if ($_cat['level'] <= $level) 
					get_sub_tree($res, $parent_id, $level, $isShowAll,$result); 
			} 
		} 
		return $result; 
	} 
} 

function remove_sub_tree(&$res, $catId, $level = 5) {				 
	foreach ($res as $key=>$_cat) { 
		if ($_cat['parent_id'] == $catId) { 
			$parent_id = $_cat['id']; 
			if ($_cat['level'] <= $level){ 
				remove_sub_tree($res, $parent_id, $level); 
			} 
			unset($res[$key]); 
		} 
	} 
	return $res; 
}

/**
 * table表格控件
 * <code>
 * $setting = array(
 * 	'attr' => array(	//table 的属性设置
 * 	)
 * 'fields'	=> array(	//table 表格字段
 * 	'id'=>array('label'=>__('ID'),'is_sort'=>true,'filter'=>false),
 *  'name'=>array('label'=>__('Name'),'is_sort'=>false,'filter'=>false),
 * ),
 * 'data' => array(
 * 	array(
 * 		'id' => 1,
 * 		'name' => 'name'
 * 	)
 * )
 * )
 * htmlTable($setting);
 * </code>
 * 
 * @param array $setting
 * @return string
 */
function htmlTable($setting) {
	$defAttr = array(
		'id'	=> 'table_items',
		'class' => 'table',
	);
	$br = "\n";
	$fields = $data = array();
	extract($setting,EXTR_OVERWRITE);
	$sort = isset( $_REQUEST['sort'] ) ? ( $_REQUEST['sort']=='asc'? 'asc': 'desc' ) : false;
	$attr = array_merge($defAttr,$attr);
	$str = '<table';
	foreach($attr as $k=>$v){
		$str .= " {$k}='{$v}'";
	}
	$str .= '>'.$br;
	
	//table header
	$str .= '<tr class="tr">'.$br;
	foreach($fields as $key=>$field){
		$str .= '<th class="th_'.$key.'">';
		$label = $field['label'];
		$isSort = isset($field['is_sort']) ?  $field['is_sort'] : false;
		if($isSort){
			if(isset($_REQUEST['order']) && $_REQUEST['order']==$key){
				 if($sort=='asc'){
				 	$label = '&#9650;'.$label;
				 }else{
				 	$label = '&#9660;'.$label;
				 }
			}
			$str .= '<a href="javascript:void(0)" class="sort_link" field="'.$key.'">'.$label.'</a>';
		}else{
			$str .= $label;
		}
		$str .= '</th>'.$br;
	}
	$str .= '</tr>'.$br;
	
	//list
	if(!empty($data)){
		foreach($data as $key=>$item){
			$id = 'tr_'.(isset($item['id']) ? $item['id'] : $key);
			
			$str .= '<tr id="'.$id.'" class="tr">'.$br;
			foreach($fields as $key=>$field){
				$str .= '<td class="td_'.$key.'">';
				if(isset($field['filter']) && !empty($field['filter'])){
					$val = $field['filter']($key,$item);
				}else{
					$val = $item[$key];
				}
				$str .= strlen($val)>0 ? $val : '&nbsp;';
				$str .= '</td>'.$br;
			}
			$str .= '</tr>'.$br;
		}
	}
	$str .= '</table>'.$br;
	return $str;
}

/**
 * 获得服务器上的 GD 版本
 *
 * @access      public
 * @return      int         可能的值为0，1，2
 */
function getGdVersion() {
	static $version = -1;

	if ($version >= 0) {
		return $version;
	}

	if (!extension_loaded('gd')) {
		$version = 0;
	} else {
		// 尝试使用gd_info函数
		if (PHP_VERSION >= '4.3') {
			if (function_exists('gd_info')) {
				$ver_info = gd_info();
				preg_match('/\d/', $ver_info['GD Version'], $match);
				$version = $match[0];
			} else {
				if (function_exists('imagecreatetruecolor')) {
					$version = 2;
				}
				elseif (function_exists('imagecreate')) {
					$version = 1;
				}
			}
		} else {
			if (preg_match('/phpinfo/', ini_get('disable_functions'))) {
				/* 如果phpinfo被禁用，无法确定gd版本 */
				$version = 1;
			} else {
				// 使用phpinfo函数
				ob_start();
				phpinfo(8);
				$info = ob_get_contents();
				ob_end_clean();
				$info = stristr($info, 'gd version');
				preg_match('/\d/', $info, $match);
				$version = $match[0];
			}
		}
	}
	return $version;
}

/**
 * 创建文件夹（级联式创建文件夹）
 * @author null
 * @param string $dir
 * @param string $mode
 * @return void;
 */
if (!function_exists('mkDirs')) {
	function mkDirs($dir, $mode = 0777) {
		$stack = array(basename($dir));
		$path = null;
		while ( ($d = dirname($dir) ) ) {
			if ( !is_dir($d) ) {
				$stack[] = basename($d);
				$dir = $d;
			} else {
				$path = $d;
				break;
			}
		}

		if ( ( $path = realpath($path) ) === false )
			return false;

		$created = array();
		for ( $n = count($stack) - 1; $n >= 0; $n-- ) {
			$s = $path . '/'. $stack[$n];
			if ( !mkdir($s, $mode) ) {
				for ( $m = count($created) - 1; $m >= 0; $m-- )
					rmdir($created[$m]);
				return false;
			}
			$created[] = $s;
			$path = $s;
		}
		return true;
	}//end function
}


/**
 * 根据ID获取该ID的存储文件相对路径
 * <code>
 * getUploadPath(1);	//返回 /000/00/00/
 * </code>
 * @param int $uid
 * @return string
 */
function getUploadPath($id) {
	$id = abs(intval($id));
	$uid = sprintf("%09d", $id);
	$dir1 = substr($uid, 0, 3);
	$dir2 = substr($uid, 3, 2);
	$dir3 = substr($uid, 5, 2);
	return $dir1 . '/' . $dir2 . '/' . $dir3 . '/';
}

/**
 * 缩略图地址
 * @param unknown $logo
 * @param string $thumb
 * @return string
 */
function getThumbFile($logo, $thumb='_thumb') {
	$pathInfo = pathinfo($logo);
	return $pathInfo['dirname'] .'/'.$pathInfo['filename'] . $thumb .'.'.$pathInfo['extension'];
}

/**
 * UTF-8截取字符串
 *
 * @param $string	待截取的字符串
 * @param $length	截取长度
 * @param $etc		截取后连接符合
 * @param $count_words	是否统计数字
 * @return String
 */
if (!function_exists('s')) {
	function s($string, $length = 80, $etc = '...', $count_words = true) {
		mb_internal_encoding("UTF-8");
		if ($length == 0)
			return '';
		if (strlen($string) <= $length)
			return $string;
		$wordscut = '';
		preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $info);
		if ($count_words) {
			$j = 0;
			for ($i = 0; $i < count($info[0]); $i++) {
				$wordscut .= $info[0][$i];
				if (ord($info[0][$i]) >= 128) {
					$j = $j +2;
				} else {
					$j = $j +1;
				}
				if ($j >= $length) {
					return $wordscut . $etc;
				}
			}
			return join('', $info[0]);
		}
		return join("", array_slice($info[0], 0, $length)) . $etc;
	}
}

if( !function_exists( 'cltime' ) ){
	function cltime($stime, $etime=0 ) {
		$etime = !empty($etime) ? $etime : time();
		if($etime<$stime) return;
		$dTime =	$etime - $stime;

		if( $dTime < 60 ){	//秒
			return "$dTime 秒前";
		}elseif( $dTime < 3600 ){	//分钟
			return intval($dTime/60).'分钟前';
		}elseif( $dTime < 86400 ){	//小时
			return intval($dTime/3600). '小时前';
		}elseif( $dTime < 2592000  ){	//��		//31536000��	 ����30��
			return intval($dTime/(3600*24)).'天前';
		}else{
			return date("Y-m-d H:i",$stime);
		}
	}
}

/**
 * 产生随机字符或者数字
 *
 * @access	public
 * @param	string
 * @return	string
 */
if (! function_exists('random')) {
	function random($length, $numeric = 0) {
		mt_srand((double)microtime() * 1000000);
		if($numeric) {
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		} else {
			$hash = '';
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
			$max = strlen($chars) - 1;
			for($i = 0; $i < $length; $i++) {
				$hash .= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}
}
function captcha($calength = 5, $namespace = 'captcha_code'){
	include_once APPPATH.'helpers/securimage/securimage.php';
	$img = new securimage();
	$img->code_length     = $calength;
	$img->namespace       = $namespace;
	//$img->ttf_file        = './Quiff.ttf';
	//$img->captcha_type    = Securimage::SI_CAPTCHA_MATHEMATIC; // show a simple math problem instead of text
	//$img->case_sensitive  = true;                              // true to use case sensitve codes - not recommended
	$img->image_height    = 36;                                // width in pixels of the image
	$img->image_width     = $img->image_height * M_E;          // a good formula for image size
	$img->perturbation    = 0.1;                               // 1.0 = high distortion, higher numbers = more distortion
	//$img->image_bg_color  = new Securimage_Color("#0099CC");   // image background color
	$img->text_color      = new Securimage_Color("#000000");   // captcha text color
	$img->num_lines       = 0;                                 // how many lines to draw over the image
	$img->line_color      = new Securimage_Color("#EAEAEA");   // color of lines over the image
	$img->image_type      = securimage::SI_IMAGE_GIF;                     // render as a jpeg image
	//$img->signature_color = new Securimage_Color(rand(0, 64),
	//                                             rand(64, 128),
	//                                             rand(128, 255));  // random signature color
		
	$img->show();
} 
function captcha_check($code, $namespace = 'captcha_code'){
	include_once APPPATH.'helpers/securimage/securimage.php';
	$img = new securimage();
	$img->namespace       = $namespace;
	if ($img->check($code) == true) {
		return true;
	}else{
		return false;
	}
}
